<template>
  <div class="app-main-container">
    <div class="warnningTip"><i class="el-icon-warning-outline" />{{ $t('message.yjdjtdsm') }}</div>
    <QueryForm
      v-model="filters"
      :query-form-config="queryFormConfig"
      @handleQuery="getList(1)"
      @clear="clear"
    />
    <div v-if="meta.indexOf('FinanceDefaultSpendAdd') > -1 || meta.indexOf('ListConsumeGeneralExport') > -1" class="doumee_table_header">
      <el-button v-if="meta.indexOf('FinanceDefaultSpendAdd') > -1" type="primary" @click="generalConsumptionAdd">{{ $t('message.add') }}</el-button>
      <el-button v-if="meta.indexOf('ListConsumeGeneralExport') > -1" :loading="exportLoading" type="primary" @click="batchexport">{{ $t('message.daochu') }}</el-button>
    </div>
    <el-table
      ref="table"
      v-loading="listLoading"
      :data="list"
      element-loading-text="Loading"
      border
      fit
      :header-row-class-name="'table-header'"
      class="doumee-element-tableb"
    >
      <el-table-column
        align="center"
        :label="$t('message.ddh')"
        show-overflow-tooltip
        prop="orderId"
        min-width="260"
      />
      <el-table-column
        align="center"
        :label="$t('message.xflx')"
        show-overflow-tooltip
        min-width="120"
        prop="type"
      />
      <el-table-column
        align="center"
        :label="$t('message.bz')"
        show-overflow-tooltip
        prop="info"
        min-width="200"
      />
      <el-table-column
        align="center"
        :label="$t('message.xfje')"
        prop="amot"
        show-overflow-tooltip
        min-width="140"
      />
      <el-table-column
        align="center"
        :label="$t('message.xfcplx')"
        prop="productType"
        show-overflow-tooltip
        min-width="120"
      >
        <template slot-scope="scope">
          <span>
            {{
              scope.row.productType == '04'
                ? $t('message.tc')
                : $t('message.kc')
            }}
          </span>
        </template>
      </el-table-column>
      <el-table-column
        align="center"
        :label="$t('message.xfcp')"
        prop="product"
        show-overflow-tooltip
        min-width="160"
      />
      <el-table-column
        align="center"
        :label="$t('message.hxzt')"
        prop="verificationStatus"
        show-overflow-tooltip
        min-width="100"
      >
        <template slot-scope="scope">
          <!-- 0/1 未核销/已核销", -->
          <span>
            {{
              scope.row.verificationStatus == 1
                ? $t('message.yhx')
                : $t('message.whx')
            }}
          </span>
        </template>
      </el-table-column>
      <el-table-column
        align="center"
        :label="$t('message.hxddh')"
        prop="relevanceOrder"
        show-overflow-tooltip
        min-width="200"
      />
      <el-table-column
        align="center"
        :label="$t('message.zflx')"
        show-overflow-tooltip
        min-width="120"
        prop="payMethodName"
      />
      <el-table-column
        align="center"
        :label="$t('message.memberInfo')"
        show-overflow-tooltip
        prop="memberInfo"
        min-width="200"
      />
      <el-table-column
        align="center"
        :label="$t('message.czy')"
        show-overflow-tooltip
        prop="creatorName"
        min-width="150"
      />
      <el-table-column
        align="center"
        :label="$t('message.createTime')"
        show-overflow-tooltip
        min-width="160"
        prop="creatorDate"
      />
      <el-table-column align="center" :label="$t('message.zfzt')" fixed="right" min-width="100">
        <template slot-scope="scope">
          <!-- 状态（1：未支付，2：已支付，3：取消支付 4：取消订单） , -->
          <span v-if="scope.row.status == 1" class="primaryColor pointer" @click="getOrderType(scope.row.orderId)">{{ $t('message.wzf') }}</span>
          <span v-else>
            {{
              scope.row.status == 1
                ? $t('message.wzf')
                : scope.row.status == 2
                  ? $t('message.yfk')
                  : scope.row.status == 3
                    ? $t('message.yqx')
                    : scope.row.status == 4
                      ? $t('message.fkyqx')
                      : ""
            }}
          </span>
        </template>
      </el-table-column>
      <el-table-column :label="$t('message.caozuo')" width="200" align="center" fixed="right">
        <template slot-scope="scope">
          <div class="flex-cc">
            <el-button
              v-if="scope.row.status == 1 && meta.indexOf('FinanceDefaultSpendPayContinue') > -1"
              v-preventReClick
              type="text"
              @click="continuePay(scope.row.orderId)"
            >{{ $t('message.jxzf') }}</el-button>
            <el-button
              v-if="scope.row.status == 1 && meta.indexOf('FinanceDefaultSpendPayCancel') > -1"
              v-preventReClick
              type="text"
              class="red"
              @click="canclePayOrder(scope.row.orderId)"
            >{{ $t('message.qxgm') }}</el-button>
            <el-button
              v-if="scope.row.status == 2 && meta.indexOf('FinanceDefaultSpendOrderCancel') > -1"
              v-preventReClick
              type="text"
              class="red"
              @click="cancleOrder(scope.row.orderId)"
            >{{ $t('message.qxdd') }} </el-button>
            <el-button
              v-if="scope.row.status == 2 && meta.indexOf('FiancePrinterOrder') > -1"
              v-preventReClick
              type="text"
              @click="printOrder(scope.row.orderId)"
            >{{ $t('message.dyxp') }}</el-button>
            <span v-if="scope.row.status > 2">-</span>
          </div>
        </template>
      </el-table-column>
    </el-table>
    <Paginations
      :total="totalCount"
      :page="pagination.page"
      @current-change="getList"
      @SizeChange="handleSizeChange"
    />
    <orderDialog ref="child" @orderSuccess="getList" />
    <GoodsTem v-if="isPrint" ref="GoodsTemRef" />
  </div>
</template>

<script>
import {
  configList,
  printOrder,
  orderType,
  listConsumeGeneralExport,
  cancleConsumeGeneral,
  infoConsumeGeneralOrder,
  listConsumeGeneral,
  noPayConsumeGeneral
} from '@/api'
import { parseTime } from '@/utils/index'
import orderDialog from '@/components/order'
import { queryFormConfig } from './config'
import GoodsTem from '@/components/printTem/goods.vue'
import QueryForm from '@/components/QueryForm'
export default {
  name: 'FinanceDefaultSpend',
  components: {
    orderDialog,
    QueryForm,
    GoodsTem
  },
  data() {
    return {
      totalCount: 0,
      queryFormConfig,
      list: [],
      isPrint: false,
      exportLoading: false,
      meta: [],
      filters: {
        time: []
      },
      listLoading: true,
      orderType: [],
      payTypeList: [],
      pagination: {
        page: 1,
        rows: 10
      },
      orderMessgae: {}
    }
  },
  created() {
    this.meta = this.$route.meta.buttons || []
    this.getList(1)
    this.getCofigList()
    // this.getOrderStatusList()
  },
  mounted() {
    this.$nextTick(() => {
      this.$refs.table.doLayout()
    })
  },
  activated() {
    if (this.$route.query.renovate) {
      this.getList(1)
    }
    this.$nextTick(() => {
      this.$refs.table.doLayout()
    })
  },
  methods: {
    // getOrderStatusList() {
    //   getOrderTypeQuery({ param: {}}).then(res => {
    //     this.queryFormConfig.formItems[3].options = res.recordList || []
    //   })
    // },
    batchexport() {
      const { filters } = this
      if (filters.time && filters.time.length > 0) {
        filters.startTime = filters.time[0]
        filters.endTime = filters.time[1]
      } else {
        filters.startTime = null
        filters.endTime = null
      }
      this.exportLoading = true
      listConsumeGeneralExport({ param: { ...filters }}).then(res => {
        this.exportLoading = false
        if (res.errorCode === '000000') {
          window.open(res.record.showUrl, '_blank')
        }
      }).catch(() => {
        this.exportLoading = false
      })
    },
    handleSizeChange(value) {
      this.pagination.rows = value
      this.getList(1)
    },
    getOrderType(orderId) {
      orderType({
        param: {
          orderId
        }
      })
        .then((res) => {
          const str = res.record.msg
          if (res.errorCode === '000000') {
            if (res.record.code === '0') {
              this.$message.success(str)
              this.getList()
            } else if (res.record.code === '2') {
              this.$message.info(str)
            } else {
              this.$message.error(str)
              this.getList()
            }
          } else {
            this.$message.error(res.msg || res.record.msg)
          }
        })
        .catch((err) => {
          console.log(err)
        })
    },
    // 获取消费类型列表
    getCofigList() {
      configList({ param: { type: '72' }})
        .then((res) => {
          if (res.errorCode !== '000000') return
          const arr = res.recordList
          arr.forEach(e => {
            e.label = e.name
            e.value = e.id
          })
          this.queryFormConfig.formItems[1].options = arr
          this.orderType = arr
        })
        .catch((err) => {
          console.log(err)
        })
      configList({ param: { type: '2', code: '1' }})
        .then(res => {
          if (res.errorCode !== '000000') return
          const arrb = res.recordList
          arrb.forEach(e => {
            e.label = e.name
          })
          this.queryFormConfig.formItems[2].options = arrb
          this.payTypeList = arrb
        }).catch(err => {
          console.log(err)
        })
    },
    // 获取通用消费列表
    getList(page) {
      const { filters, pagination } = this
      if (filters.time && filters.time.length > 0) {
        filters.startTime = filters.time[0]
        filters.endTime = filters.time[1]
      } else {
        filters.startTime = null
        filters.endTime = null
      }
      if (page) {
        pagination.page = page
        this.pagination.page = Number(page)
      }
      pagination.firstQueryTime = parseTime(new Date())
      this.listLoading = true
      listConsumeGeneral({
        pagination,
        param: { ...filters },
        userId: sessionStorage.getItem('userId')
      })
        .then((res) => {
          this.listLoading = false
          if (res.errorCode !== '000000') return
          this.list = res.recordList
          this.totalCount = res.totalCount
          if (res.totalCount && res.recordList.length === 0 && pagination.page > 1) {
            this.getList(Math.ceil(res.totalCount / pagination.rows))
          }
        })
        .catch((err) => {
          console.log(err)
          this.listLoading = false
        })
    },
    // 清空
    clear() {
      this.filters = { time: [] }
      this.getList(1)
    },
    generalConsumptionAdd() {
      this.$router.push({ name: 'FinanceDefaultSpendAdd' })
    },
    // 打印小票
    printOrder(orderId) {
      this.$confirm(this.$t('message.dyxptc'), this.$t('message.ts'), {
        confirmButtonText: this.$t('message.qd'),
        cancelButtonText: this.$t('message.qx'),
        type: 'warning'
      })
        .then(() => {
          this.isPrint = true
          printOrder({
            param: {
              contentMap: {},
              venueId: sessionStorage.getItem('venueId'),
              workId: orderId,
              templateCode: 'CONSUMETPML'
            }
          })
            .then((res) => {
              if (res.record && res.record.isPrint === '1' && res.record.dataList && res.record.dataList.length > 0) {
                res.record.dataList.forEach(item => {
                  this.$refs.GoodsTemRef.obj = { ...item }
                  setTimeout(() => {
                    this.$refs.GoodsTemRef.print()
                  }, 300)
                  setTimeout(() => {
                    this.isPrint = false
                  }, 500)
                })
              } else {
                this.isPrint = false
              }
            })
            .catch((err) => {
              this.isPrint = false
              console.log(err)
            })
        })
        .catch(() => {
          // this.$message.info('操作已取消')
        })
    },
    // 取消支付
    canclePayOrder(orderId) {
      const that = this
      this.$confirm(this.$t('message.qxgmtc'), this.$t('message.ts'), {
        confirmButtonText: this.$t('message.qd'),
        cancelButtonText: this.$t('message.qx'),
        type: 'warning',
        callback: () => {},
        beforeClose: (action, ctx, close) => {
          if (action !== 'confirm') {
            close()
            return
          }
          ctx.confirmButtonLoading = true
          noPayConsumeGeneral({ param: { orderId }}).then((res) => {
            ctx.confirmButtonLoading = false
            close()
            if (res.errorCode === '000000') {
              that.$message.success(this.$t('message.qxcg'))
              that.getList()
            }
          })
            .catch(() => { ctx.confirmButtonLoading = false })
        }
      }).finally(() => {})
    },
    // 取消订单
    cancleOrder(orderId) {
      const that = this
      this.$confirm(this.$t('message.qxddtc'), this.$t('message.ts'), {
        confirmButtonText: this.$t('message.qd'),
        cancelButtonText: this.$t('message.qx'),
        type: 'warning',
        callback: () => {},
        beforeClose: (action, ctx, close) => {
          if (action !== 'confirm') {
            close()
            return
          }
          ctx.confirmButtonLoading = true
          cancleConsumeGeneral({ param: { orderId }}).then((res) => {
            ctx.confirmButtonLoading = false
            close()
            if (res.errorCode === '000000') {
              that.$message.success(this.$t('message.qxcg'))
              that.getList()
            }
          })
            .catch(() => { ctx.confirmButtonLoading = false })
        }
      }).finally(() => {})
    },
    // 继续支付
    continuePay(orderId) {
      infoConsumeGeneralOrder({
        param: {
          orderId: orderId,
          venueId: sessionStorage.getItem('venueId')
        },
        userId: sessionStorage.getItem('userId')
      })
        .then((res) => {
          if (res.errorCode === '000000') {
            this.orderMessgae = res.record
            this.$refs.child.continuePay(res.record, 'financeDefaultSpend')
          }
        })
        .catch((err) => {
          console.log(err)
        })
    }
  }
}
</script>
<style lang="scss" scoped>

</style>
